//
//  PlaytimeUploader.swift
//  GhostWorld
//
//  Created by Kam on 2018/7/18.
//  Copyright © 2018 LKGood. All rights reserved.
//

import Foundation

class PlaytimeManager {
  // MARK: - Singleton
  static let shared = PlaytimeManager()
  private init() { }
  
  func save(audioID: Int, seconds: Int) {
    if UserManager.shared.currentUser != nil {
      do {
        try Playtime.add(audioID: audioID, seconds: seconds)
        upload()
      } catch { }
    }
  }
  
  func upload() {
    if let playtime = EntityManager.fetch(Playtime.self, fetchType: .all)?.first {
      API.shared.requestAPI (
        APIURLStrings.uploadPlaytime(audioIdentifier: Int(playtime.audioID)),
        method: .post,
        body: ["seconds": Int(playtime.seconds)],
        header: API.shared.memeberHeader,
        successCallback: { _ in
          do {
            try Playtime.remove(playtime)
            self.upload()
          } catch { }
      }) { (message, code) in
        loggingPrint("Upload playtime failed. \(message)")
      }
    }
  }
}
